<?php

declare(strict_types=1);

namespace App\Services\Logistics;

use App\Constants\AliCloud\LogisticsCode;
use App\Utils\Other\AliCloud\Logistics\Logistics;
use App\Utils\Services\BaseServices;
use App\Model\Logistics\Logistic as LogisticModel;
use Psr\SimpleCache\CacheInterface;

/**
 * Class Logistic
 * @author zx
 * @package App\Services\Logistics
 */
Class Logistic extends BaseServices
{
    public function __construct(
        protected CacheInterface $cache,
        protected Logistics $logistics
    )
    {
        parent::__construct();
    }

    public function model():string
    {
        return LogisticModel::class;
    }

    /**
     * 获取物流详情
     * @param string $no
     * @param string $type
     * @param string $mobile
     * @return array|mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Throwable
     */
    public function getInfo(string $no, $type='', $mobile='')
    {
        $keyName = 'express_cache_'.$no;
        if ($this->cache->has($keyName)) {
            return $this->cache->get($keyName);
        }
        if ($type === 'STO') {
            $no .= ':'.substr($mobile, -4);
        }
        /** @var LogisticModel $logisticsModel */
        $logisticsModel = $this->where('no', $no)
            ->where('code', $type)
            ->first();
        if ($logisticsModel &&
            in_array($logisticsModel->delivery_status, [
                LogisticsCode::DELIVERY_STATUS_SIGNED_IN,
                LogisticsCode::DELIVERY_STATUS_RETURN_RECEIPT])) {
            $this->cache->set($keyName, $logisticsModel->response);
            return $logisticsModel->response;
        }
        $response = $this->logistics->handle(compact('no', 'type'));
        if ($logisticsModel) {
            $logisticsModel->fill([
                'delivery_status' => $response['deliverystatus'],
                'response' => $response
            ])->save();
            $logisticsModel->increment('frequency_num');
        } else {
            $this->create([
                'no' => $no,
                'code' => $type,
                'delivery_status' => $response['deliverystatus'],
                'courier_phone' => $response['courierPhone'],
                'response' => $response,
                'frequency_num' => 1
            ]);
        }
        $this->cache->set(
            $keyName,
            $response,
            in_array($response['deliverystatus'], [
                LogisticsCode::DELIVERY_STATUS_SIGNED_IN,
                LogisticsCode::DELIVERY_STATUS_RETURN_RECEIPT])?null:3600);

        return $response;
    }
}
